<template>
  <view class="shop-detail-container">
    <!-- 店铺头部信息 -->
    <view class="shop-header">
      <image :src="shop.imgUrl" mode="aspectFit" class="shop-logo"></image>
      <view class="shop-header-text">
        <text class="shop-name">{{ shop.name }}</text>
        <view class="shop-info">
          <text>月售: {{ shop.sales }} 起送: {{ shop.expressLimit }} 基础运费:{{ shop.expressPrice }}</text>
          <text class="promotion" v-if="shop.slogan">{{ shop.slogan }}</text>
        </view>
      </view>
    </view>
    <!-- 商品分类和商品列表 -->
    <view class="category-container">
      <view class="category-menu">
        <view
          class="category-item"
          v-for="(category, index) in categories"
          :key="index"
          :class="{ active: currentCategory === index }"
          @click="switchCategory(index)"
        >
          <text class="category-name">{{ category.name }}</text>
        </view>
      </view>
      <view class="product-list">
        <view
          class="product-item"
          v-for="(product, productIndex) in currentProducts"
          :key="product.id"
        >
          <image
            :src="product.imgUrl"
            mode="aspectFit"
            class="product-image"
          ></image>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <text class="monthly-sales-text">月售 {{ product.sales }} 件</text>
            <div class="price-container">
              <text class="product-price">¥{{ product.price }}</text>
              <text class="original-price" v-if="product.oldPrice">¥{{ product.oldPrice }}</text>
            </div>
          </view>
          <!-- 加入购物车按钮 -->
          <button class="add-to-cart-button" @click="addToCart(product)">+</button>
        </view>
      </view>
    </view>
    <!-- 购物车和总计信息 -->
    <view class="cart-total">
      <view class="cart-icon" @click="showCartPopup = true; fetchCartData()">
        <image src="../../static/icons/cart.png" mode="aspectFit"></image>
        <text class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</text>
      </view>
      <button class="settlement-button" @click="goToCartPage">查看购物车</button>
    </view>
    <!-- 弹出框 -->
    <view class="cart-popup" :class="{ show: showCartPopup }">
      <view class="popup-header">
        <text>购物车</text>
        <button @click="showCartPopup = false" class="asd">关闭</button>
      </view>
      <view
        class="popup-product-item"
        v-for="(cartItem, index) in filteredCartItems"
        :key="index"
      >
        <image
          :src="cartItem.imgUrl"
          mode="aspectFit"
          class="popup-product-image"
        />
        <view class="popup-product-info">
          <text class="popup-product-name">{{ cartItem.name }}</text>
          <text class="popup-product-quantity">数量: {{ cartItem.quantity }}</text>
          <br>
          <text class="popup-product-price">单记：¥{{ cartItem.price *  cartItem.quantity}}</text> <!-- 显示商品价格 -->
        </view>
      </view>
      <view class="total-price-container"> <!-- 总价格容器 -->
        <text class="total-price">总价: ¥{{ totalPrice }}</text> <!-- 显示总价格 -->
      </view>
      <button class="checkout-button" @click="goToOrderPayPage">去结算</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shop: {},
      cartCount: 0,
      categories: [
        { name: "全部商品", products: [] },
        { name: "秒杀", products: [] },
        { name: "新鲜水果", products: [] },
      ],
      currentCategory: 0,
      currentProducts: [],
      groupedCartProducts: [],
      showCartPopup: false,
      cartItems: [],
      filteredCartItems: [],
      totalPrice: 0 // 添加总价格变量
    };
  },
  onLoad(options) {
    const shopId = options.id;
    this.fetchShopDetail(shopId);
  },
  methods: {
    async fetchShopDetail(shopId) {
      try {
        const response = await this.$axios.get(`http://localhost:3000/shops/${shopId}`);
        this.shop = response.data;

        const allProducts = await this.$axios.get("http://localhost:3000/products-all");
        const seckillProducts = await this.$axios.get("http://localhost:3000/products-seckill");
        const fruitProducts = await this.$axios.get("http://localhost:3000/products-fruit");

        const filteredAllProducts = allProducts.data.filter((product) => product.shopId === shopId);
        const filteredSeckillProducts = seckillProducts.data.filter((product) => product.shopId === shopId);
        const filteredFruitProducts = fruitProducts.data.filter((product) => product.shopId === shopId);

        this.categories[0].products = filteredAllProducts;
        this.categories[1].products = filteredSeckillProducts;
        this.categories[2].products = filteredFruitProducts;

        this.currentProducts = this.categories[0].products;
      } catch (error) {
        console.error("获取店铺详情失败", error);
      }
    },
    switchCategory(index) {
      this.currentCategory = index;
      this.currentProducts = this.categories[index].products;
    },
    async addToCart(product) {
      try {
        const cartItems = await this.$axios.get("http://localhost:3000/cart");
        const existingItem = cartItems.data.find((item) => item.id === product.id);
        if (existingItem) {
          const updatedQuantity = existingItem.quantity + 1;
          const mergedProduct = {
           ...existingItem,
           ...product,
            quantity: updatedQuantity,
          };
          await this.$axios.put(`http://localhost:3000/cart/${existingItem.id}`, mergedProduct);
          const shopIndex = this.findShopIndexByProductId(product.id);
          if (shopIndex!== -1) {
            const itemIndex = this.findItemIndexInShop(shopIndex, product.id);
            if (itemIndex!== -1) {
              this.groupedCartProducts[shopIndex].products[itemIndex] = mergedProduct;
            }
          }
        } else {
          await this.$axios.post("http://localhost:3000/cart", product);
          const newCartItem = {
           ...product,
            isSelected: true,
            quantity: 1
          };
          const shopIndex = this.findShopIndexByProductId(product.id);
          if (shopIndex!== -1) {
            this.groupedCartProducts[shopIndex].products.push(newCartItem);
          } else {
            const newShopGroup = {
              shopName: product.shopName,
              shopId: product.shopId,
              isAllSelected: true,
              products: [newCartItem],
              totalPrice: 0,
              selectedProductId: null,
            };
            this.groupedCartProducts.push(newShopGroup);
          }
        }
        console.log("商品已加入购物车");
        await this.updateCartCount();
        this.updateTotalPrice(); // 更新总价格
        this.$forceUpdate(); 
      } catch (error) {
        console.error("加入购物车失败", error);
      }
    },
    async updateCartCount() {
      try {
        const response = await this.$axios.get("http://localhost:3000/cart");
        const cartItems = response.data;
        const currentShopId = this.shop.id;
        this.cartCount = 0;
        cartItems.forEach((item) => {
          if (item.shopId === currentShopId) {
            this.cartCount += item.quantity;
          }
        });
      } catch (error) {
        console.error("获取购物车数据失败", error);
      }
    },
    goToCartPage() {
      uni.switchTab({
        url: "/pages/cart/cart?refresh=true",
      });
    },
    findShopIndexByProductId(productId) {
      return this.groupedCartProducts.findIndex((shopGroup) => {
        return shopGroup.products.some((product) => product.id === productId);
      });
    },
    findItemIndexInShop(shopIndex, productId) {
      return this.groupedCartProducts[shopIndex].products.findIndex((product) => product.id === productId);
    },
    async fetchCartData() {
      try {
        const response = await this.$axios.get("http://localhost:3000/cart");
        this.cartItems = response.data;
        this.filteredCartItems = this.cartItems.filter(item => item.shopId === this.shop.id);
        this.updateTotalPrice(); // 更新总价格
      } catch (error) {
        console.error("获取购物车数据失败", error);
      }
    },
    goToOrderPayPage() {
      // 获取弹出框中购物车商品的信息
      const selectedCartItems = this.filteredCartItems.map(item => item.id);
      uni.switchTab({
        url: `/pages/cart/cart?selectedItems=${selectedCartItems.join(',')}&refresh=true`
      });
    },
    updateTotalPrice() {
      this.totalPrice = this.filteredCartItems.reduce((acc, item) => acc + (item.price * item.quantity), 0);
    }
  },
  watch: {
    currentProducts: {
      deep: true,
      handler() {
        this.updateCartCount();
      },
    },
    filteredCartItems: {
      deep: true,
      handler() {
        this.updateTotalPrice();
      }
    }
  },
};
</script>



<style scoped>

.checkout-button {
  background-color: #4aa4f3;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
  display: block;
  width: 100%;
  text-align: center;
}

.asd {
  margin-right: unset;
}

page {
  background-color: #f8f8f8;
}

/* 整体容器样式 */
.shop-detail-container {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin: 20px;
  padding-bottom: 60px; 
}

/* 店铺头部样式 */
.shop-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.shop-logo {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  margin-right: 20px;
  object-fit: cover;
}

.shop-header-text {
  flex: 1;
}

.shop-name {
  font-size: 24px;
  color: #333;
  font-weight: 700;
  margin-bottom: 5px;
}

.shop-info {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.promotion {
  color: #ff5722;
  font-weight: 500;
  margin-top: 5px;
  display: block;
}

/* 商品分类菜单样式 */
.category-container {
  display: flex;
  margin-top: 20px;
}

.category-menu {
  width: 130px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); 
  margin-right: 20px;
  overflow: hidden;
}

.category-item {
  padding: 15px;
  cursor: pointer;
  text-align: center;
  transition: background-color 0.3s ease;
}

.category-item:hover {
  background-color: #f0f0f0;
}

.category-item.active {
  background-color: #4aa4f3;
  color: #fff;
}

.category-name {
  font-size: 16px;
  font-weight: 500;
}

/* 商品列表样式 */
.product-list {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); 
  padding: 15px;
}

.product-item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding: 15px 0;
  transition: transform 0.3s ease;
}

.product-item:last-child {
  border-bottom: none;
}

.product-item:hover {
  transform: translateY(-3px);
}

.product-image {
  width: 90px;
  height: 90px;
  border-radius: 8px;
  margin-right: 20px;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 18px;
  color: #333;
  font-weight: 600;
  margin-bottom: 5px;
}

.product-info {
  flex: 1;
  font-size: 12px;
}

.price-container {
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.product-price {
  color: #ff5722;
  font-size: 18px;
  font-weight: 600;
  margin-right: 10px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 14px;
}

.add-to-cart-button {
  background-color: #4aa4f3;
  color: white;
  border: none;
  width: 32px; 
  height: 32px;
  border-radius: 50%; 
  cursor: pointer;
  margin-left: auto;
  font-size: 16px; 
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 购物车和总计样式 */
.cart-total {
  display: flex;
  align-items: center;
  justify-content: space-between; 
  background-color: #fff;
  padding: 15px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin: 20px;
  position: fixed; 
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000; 
}

.cart-icon {
  display: flex;
  align-items: center;
}

.cart-icon image {
  width: 35px;
  height: 35px;
  margin-right: 10px;
}

.cart-badge {
  background-color: #4aa4f3;
  color: #fff;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 50%;
}

.settlement-button {
  background-color: #4aa4f3;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 0.5%;
  margin-left: auto; 
}

/* 弹出框样式 */
.cart-popup {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 12px 12px 0 0;
  box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.1);
  z-index: 1001;
  padding: 15px;
  transform: translateY(100%);
  transition: transform 0.3s ease;
  display: flex;
  flex-direction: column;
}

.cart-popup.show {
  transform: translateY(0);
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.popup-product-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.popup-product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 15px;
  object-fit: cover;
}

.popup-product-info {
  flex: 1;
}

.popup-product-name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  margin-bottom: 5px;
}

.popup-product-quantity {
  font-size: 14px;
  color: #666;
}

.popup-product-price {
  font-size: 14px;
  color: #ff5722;
}

.total-price-container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.total-price {
  font-size: 18px;
  color: #333;
  font-weight: 600;
}    
</style>    